package cn.gcsts.misky.gradle.webmodule

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction


class InstallWebModuleTask extends DefaultTask {
	/** default work directory **/
	def String wmTempDir = "${project.buildDir}/wm_work_temp";
	/** 更新webmodule时，是否替换项目中已存在的资源目录下的文件。 false 不替换[默认], true替换所有配置文件 **/
	def boolean overiteExistsResources = false;
	/** 要排除的资源文件 **/
	def String[] resourceExclude;
	
	@TaskAction
	def install() {
		def  configurations = project.configurations;
		def  buildDir = project.buildDir
		def  webAppDir = project.webAppDir
		
		configurations.webmodules.each { f ->
			
			def jar = new java.util.jar.JarFile(f)
			def attrs = jar.manifest.getAttributes(WebModuleTask.SECTION_NAME);
			
			// 不是webmodule
			if (attrs == null || attrs.isEmpty()) {
				return;
			}
			
			def moduelName = attrs.getValue("Module-Name");
			
			// 不是web module
			if (moduelName == null || moduelName.empty) {
				return;
			}
			
			project.copy {
				from project.zipTree(f)
				into wmTempDir
			}
			
			project.copy {
				from "$wmTempDir/webviews"
				into "$webAppDir"
			}
			
			project.copy {
				from "$wmTempDir/java-resources"
				into project.sourceSets.main.resources.srcDirs[0]
				eachFile {t ->
					if (overiteExistsResources) return;
					if (new File(project.sourceSets.main.resources.srcDirs[0], t.sourcePath).exists()) {
						t.exclude()
					}
				}
				if (resourceExclude != null) {
					exclude resourceExclude
				}
			}	
			
			project.delete wmTempDir
			
		}
	}
}